<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type { TApiResponseData } from '@/types/global'
import type { TCategoryItem, TBannerItem, THotItem } from '@/types/home'
import Api from '@/services/index'
import HotPanel from './components/HotPanel.vue'
import XtxGuess from '@/components/XtxGuess.vue'
import XtxBanner from '@/components/XtxBanner.vue'
import HomeSkeleton from './components/HomeSkeleton.vue'
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import { useGuessList } from '@/composables'

const bannerList = ref<TBannerItem[]>([])
const categoryList = ref<TCategoryItem[]>([])
const hotList = ref<THotItem[]>([])
const isTriggered = ref(false)
const loading = ref(true)
// 猜你喜欢-组合式函数
const { xtxguessRef, onScrollToLower } = useGuessList()

// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开启动画
  isTriggered.value = true
  // 重置猜你组件数据
  xtxguessRef.value?.resetData()
  // 等待数据加载
  await Promise.all([getBannerList(), getCategoryList(), getHotList()])
  isTriggered.value = false
}

const getBannerList = async () => {
  const res: TApiResponseData<TBannerItem[]> = await Api.HomeAPI.getBannerList()
  bannerList.value = res.result
}

const getCategoryList = async () => {
  const res: TApiResponseData<TCategoryItem[]> = await Api.HomeAPI.getCategoryList()
  categoryList.value = res.result
}

const getHotList = async () => {
  const res: TApiResponseData<THotItem[]> = await Api.HomeAPI.getHotList()
  hotList.value = res.result
}
onLoad(async () => {
  loading.value = true
  await Promise.all([getBannerList(), getCategoryList(), getHotList()])
  loading.value = false
})
</script>

<template>
  <CustomNavbar></CustomNavbar>

  <scroll-view
    scroll-y
    class="main"
    enable-flex
    lower-threshold="10"
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
    @scrolltolower="onScrollToLower"
  >
    <HomeSkeleton v-if="loading"></HomeSkeleton>
    <template v-else>
      <view class="banner">
        <XtxBanner :list="bannerList"></XtxBanner>
      </view>
      <CategoryPanel :list="categoryList"></CategoryPanel>
      <HotPanel :list="hotList"></HotPanel>
      <XtxGuess ref="xtxguessRef"></XtxGuess>
    </template>
  </scroll-view>
</template>

<style lang="scss" scoped>
@import './styles/index';
</style>
